<?php 

	if(!defined('YMT')) exit;

	require_once('Smarty/Smarty.class.php');
	
	/**
	 * @package Yomm
	 * @author bsuter
	 * Yomm_View requires the Smarty Template Engine which must be include before the Class.
	 */
	Class Yomm_View Extends Smarty
	{

		public $theme = null;
		
		private $_js = array();
		
		private $_css = array();
		
		public function __construct($theme)
		{
			// call the parent Smarty constrcutor
			parent::__construct();
			
			// set the theme for this View from $theme
			$this->theme = 'theme/' . $theme;
			
			// define and configure the variables which are need for Smarty to run.
			$this->compile_dir = Yomm_Config::DIR_TEMPLATE_COMPILE;
			$this->cache_dir = Yomm_Config::DIR_CACHE;
			$this->template_dir = $this->theme . '/tpl/';
		}
		
		public function setTheme ($theme) {
			$this->theme = 'theme/' . $theme;
			$this->template_dir = $this->theme . '/tpl/';
		}
		
		/**
		 * Old name was: add_js change it!
		 * @param $js [text] full path or what??
		 */
		public function addJs($js)
		{
			$this->_js[] = $js;
		}
		
		public function addCss($css)
		{
			$this->_css[] = $css;
		}
		
		public function show($tpl)
		{
			$this->assign(array(
				'js_files' => $this->_js,
				'css_files' => $this->_css
			));
			
			/* check if template file existst */
			if(file_exists($this->template_dir . $tpl))
			{
				return $this->fetch($tpl);
			}
			
			$this->template_dir = $this->theme . '/';
			
			if(file_exists($this->template_dir . $tpl))
			{
				return $this->fetch($tpl);
			}
			
			return "the template '{$tpl}' can not be found in your theme folder '{$this->theme}'";
			
		}
		
		/**
		 * if it should no overwrite already existing variables in template use notAppend(array $array)
		 * 
		 * @param $array [array] assign key => assign value
		 */
		public function notAppend(array $array)
		{
			foreach($array as $key => $value)
			{
				if(!isset($this->tpl_vars[$key]))
				{
					$this->assign($key, $value);
				}
			}
		}
		
		/**
		 * @param $key [string] the name of the variabel 
		 * @param $value [array] the values of the array to write over like: array('conten1' => 'the value of content1');
		 */
		public function append_over($key, array $value)
		{
			// the first append of this key - just make an assign
			if(!isset($this->tpl_vars[$key]))
			{
				//echo "assign of $key : "; print_r($value);
				$this->assign($key, $value);
				return true;
			}
			
			// the variable is already in the tpl system. now we just have to append the array values of the value
			$_vars = $this->tpl_vars[$key]->value;
			
			
			foreach($value as $k => $i)
			{
				$_vars[$k] = $i;
			}
			
			$this->assign($key, $_vars);
		}
		
	}